package com.Realm;

import com.domain.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import com.service.IUserService;

import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @author: wu linchun
 * @time: 2021/4/4 20:28
 */

public class UserRealm extends AuthorizingRealm {
    @Autowired
    IUserService iUserService;

    public UserRealm() {
    }

    /*@Autowired    UserRealm类不能用构造方法进行bean注入
    public UserRealm(IUserService iUserService) {
        this.iUserService = iUserService;
    }*/
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=>授权doGetAuthorizationInfo");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获取当前用户subject
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();
        String[] perms = currentUser.getPower().split(",");
        List<String> permslist = new ArrayList<String>();
        for (String s : perms) {
            permslist.add(s);
        }
        /*for(String s:perms){    //如果是对一个角色授予多个权限，则不可以使用addStringPermission像这样子授权
            System.out.println(s);
            info.addStringPermission(s);
        }*/
        info.addStringPermissions(permslist);   // addStringPermission：添加单个权限。addStringPermissions：添加多个权限
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了=>认证doGetAuthorizationInfo");
        /*String username = "root";
        String password = "123456";*/
        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
        User user = iUserService.queryUserbyUserName(userToken.getUsername());
        if (user == null) {
            return null;
        }
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute("user_session", user);
        session.setAttribute("id_session", user.getId());
        /*if (!usernamePasswordToken.getUsername().equals(username)) {
            return null;
        }*/
        //密码认证，shiro做
        return new SimpleAuthenticationInfo(user, user.getPassword(), "");
    }
}
